<template>
  <j-modal
    :title="title"
    :width="1200"
    :visible="visible"
    :maskClosable="false"
    :destroyOnClose="true"
    :confirmLoading="confirmLoading"
    @ok="handleOk"
    @cancel="handleCancel"
  >
    <a-spin :spinning="confirmLoading">
      <!-- 主表单区域 -->
      <a-form :form="form">
        <a-row>
          <a-col :span="12">
            <a-form-item label="商机名称" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input
                :disabled="disableSubmit"
                v-decorator="['businessName', validatorRules.businessName]"
                placeholder="请输入商机名称"
              ></a-input>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="销售阶段" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-select
                :disabled="disableSubmit"
                style="width: 100%"
                v-decorator="['statusId', { initialValue: '0', rules: validatorRules.statusId.rules }]"
                @change="chanageDealStatus"
              >
                <!--
                 <a-select-option value="0">验证客户</a-select-option>
                 <a-select-option value="1">需求分析</a-select-option>
                 <a-select-option value="2">方案/报价</a-select-option>
                 <a-select-option value="3">投标中</a-select-option>
                 <a-select-option value="4">已签约</a-select-option>
		 <a-select-option value="6">入仓</a-select-option>
                 -->
                <a-select-option value="0">需求发现</a-select-option>
                <a-select-option value="1">看仓</a-select-option>
                <a-select-option value="2">需求明确</a-select-option>
                <a-select-option value="3">报价或投标</a-select-option>
                <a-select-option value="4">中标</a-select-option>
                <a-select-option value="5">签约</a-select-option>

                <a-select-option value="7">失败</a-select-option>
              </a-select>
              <!-- .. -->
              <a-input-number
                v-show="false"
                :min="0"
                :max="100"
                style="width: 0"
                :disabled="disableSubmit"
                v-decorator="['followup', { initialValue: 10 }]"
                placeholder="请输入跟进状态"
              ></a-input-number>
            </a-form-item>
          </a-col>
          <a-col :span="12" v-if="status5TimeVisible">
            <a-form-item label="签约时间" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <j-date
                placeholder="请选择签约时间"
                :show-time="true"
                v-decorator="['status5Time', status5TimeVisible ? validatorRules.status5Time : null]"
                :trigger-change="true"
                date-format="YYYY-MM-DD HH:mm:ss"
                style="width: 100%"
              />
            </a-form-item>
          </a-col>
<!--          <a-col :span="12" v-if="status6TimeVisible">-->
<!--            <a-form-item label="入仓时间" :labelCol="labelCol" :wrapperCol="wrapperCol">-->
<!--              <j-date-->
<!--                placeholder="请选择入仓时间"-->
<!--                :show-time="true"-->
<!--                v-decorator="['status6Time', status6TimeVisible ? validatorRules.status6Time : null]"-->
<!--                :trigger-change="true"-->
<!--                date-format="YYYY-MM-DD HH:mm:ss"-->
<!--                style="width: 100%"-->
<!--              />-->
<!--            </a-form-item>-->
<!--          </a-col>-->
<!--:dict="'CrmCustomer,customerName,id' + (groupId === '4210' ? ',ownerUserId=' + ownerUserId : '')"-->
          <a-col :span="12">
            <a-form-item label="客户" v-if="customerId && !model.id" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <j-search-select-tag
                :disabled="true"
                type="list"
                :dictOptions="customerInfoList"
                v-decorator="['customerId', validatorRules.customerId]"
              />
            </a-form-item>
            <a-form-item label="客户" v-else :labelCol="labelCol" :wrapperCol="wrapperCol">
              <j-search-select-tag
                :disabled="disableSubmit"
                type="list"
                v-decorator="['customerId', validatorRules.customerId]"
                :trigger-change="true"
                placeholder="请选择客户"
                :dictOptions="customerInfoList"
              />
            </a-form-item>
          </a-col>

          <!-- <a-col :span="12">
            <a-form-item label="联系人" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <j-search-select-tag
                :disabled="disableSubmit"
                type="list"
                v-decorator="['contactsId']"
                dict="CrmContacts,name,id"
              />
            </a-form-item>
          </a-col> -->

          <a-col :span="12">
            <a-form-item label="销售进展" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-textarea
                :disabled="disableSubmit"
                v-decorator="['remark', validatorRules.remark]"
                placeholder="请输入销售进展"
              ></a-textarea>
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>

      <!-- 子表单区域 -->
      <a-tabs v-model="activeKey" @change="handleChangeTabs">
        <a-tab-pane v-for="(item, index) in itemList" :tab="item.title" :key="item.key" :forceRender="true">
          <j-editable-table
            :disabled="disableSubmit"
            :ref="item.key"
            :tableName="item.title"
            :loading="item.loading"
            :columns="item.columns"
            :dataSource="item.dataSource"
            :maxHeight="300"
            :rowNumber="true"
            :rowSelection="true"
            :actionButton="true"
            @valueChange="itemChange"
          />
        </a-tab-pane>
      </a-tabs>
    </a-spin>
  </j-modal>
</template>

<script>
import pick from 'lodash.pick'
import { FormTypes, getRefPromise } from '@/utils/JEditableTableUtil'
import { JEditableTableMixin } from '@/mixins/JEditableTableMixin'
import { validateDuplicateValue } from '@/utils/util'
import JDate from '@/components/jeecg/JDate'
import JDictSelectTag from '@/components/dict/JDictSelectTag'
import JSearchSelectTag from '@/components/dict/JSearchSelectTag'
import { getAction, httpAction } from '@/api/manage'
import { mapGetters } from 'vuex'
export default {
  name: 'CrmBusinessModal',
  mixins: [JEditableTableMixin],
  components: {
    JDate,
    JDictSelectTag,
    JSearchSelectTag,
  },
  props: {
    customerId: {
      type: String,
      default: '',
    },
    businessId: {
      type: String,
      default: '',
    },
  },
  data() {
    return {
      inventoryIdOptions: [],
      transTypeOptions: [],
      forwardingTypeOptions: [],
      shoppingTypeOptions: [],
      isImportOptions: [],
      ownerUserId: this.userInfo().userLoginId,
      groupId: this.userInfo().groupId,
      disableSubmit: false,
      status5TimeVisible: false,
      status6TimeVisible: false,
      labelCol: {
        xs: { span: 24 },
        sm: { span: 6 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
      },
      labelCol2: {
        xs: { span: 24 },
        sm: { span: 3 },
      },
      wrapperCol2: {
        xs: { span: 24 },
        sm: { span: 20 },
      },
      // 新增时子表默认添加几行空数据
      addDefaultRowNum: 0,
      validatorRules: {
        businessName: {
          rules: [{ required: true, message: '请输入商机名称!' }],
        },
        statusId: {
          rules: [{ required: true, message: '请选择销售阶段!' }],
        },

        customerId: {
          rules: [{ required: true, message: '请选择客户!' }],
        },
        status5Time: {
          rules: [{ required: true, message: '请选择签约时间!' }],
        },
        // status6Time: {
        //   rules: [{ required: true, message: '请选择入仓时间!' }],
        // },
        remark: {
          rules: [{ required: true, message: '请输入销售进展!' }],
        },
      },
      //refKeys: ['item1'],
      refKeys: ['item1', 'item2', 'item3', 'item4'],
      tableKeys: ['item1', 'item2', 'item3', 'item4'],
      activeKey: 'item1',
      itemList:[],
      customerList:[],
      customerInfoList:[],
      url: {
        add: '/online/special/api/createCrmBusiness',
        edit: '/online/special/api/updateCrmBusiness',
        list: '/online/api/viewCrmBusinessItemById',
      },
    }
  },
  created() {
    this.loadItem()
  },
  methods: {
    ...mapGetters(['userInfo']),
    loadItem() {
      let that = this;
      //customerList
       // :dict="'CrmCustomer,customerName,id' + (groupId === '4210' ? ',ownerUserId=' + ownerUserId : '')"
      let queryParam = {
        ownerUserId: this.userInfo().userLoginId,
      };


      this.$bus.on('superParam', function (param) {
        if (param.type == 1) {
          if (param.data != 0) {
            queryParam.ownerUserIdList = param.data
            getAction('/online/api/listByUserIdCrmCustomer', queryParam).then((res) => {
              if (res.success) {
                that.customerList = res.result;
              }
            })
          }
        }
      })


      getAction('/online/api/orderByCrmWmsInventory2', {}).then((res) => {
        if (res.success) {
          this.inventoryIdOptions = res.result
        }
      })
      getAction('/online/dict/getDictItems/DataDictionary,description,dictionaryCode,dictionaryTypeId=TRANS_TYPE', {
        otherField: '',
      }).then((res) => {
        if (res.success) {
          this.transTypeOptions = res.result
        }
      })
      getAction('/online/dict/getDictItems/DataDictionary,description,dictionaryCode,dictionaryTypeId=FWD_TYPE', {
        otherField: '',
      }).then((res) => {
        if (res.success) {
          this.forwardingTypeOptions = res.result
        }
      })
      getAction('/online/dict/getDictItems/DataDictionary,description,dictionaryCode,dictionaryTypeId=SHOP_TYPE', {
        otherField: '',
      }).then((res) => {
        if (res.success) {
          this.shoppingTypeOptions = res.result
        }
      })
      getAction('/online/dict/getDictItems/DataDictionary,description,dictionaryCode,dictionaryTypeId=IMPORT_TYPE', {
        otherField: '',
      }).then((res) => {
        if (res.success) {
          this.isImportOptions = res.result
        }
      })
    },
    async itemChange(event) {
      console.log(event)
      const { type, row, column, value, target } = event
      if (column.key === 'discount' || column.key === 'num' || column.key === 'salesPrice') {
        let discount = row.discount
        if (!discount) discount = 0
        let num = row.num
        if (!num) num = 0
        let salesPrice = row.salesPrice
        if (!salesPrice) salesPrice = 0
        let subtotal = (parseFloat(discount) * parseFloat(num) * parseFloat(salesPrice)) / 100
        target.setValues([
          {
            rowKey: row.id,
            values: { subtotal: subtotal },
          },
        ])
      }
    },
    getAllTable() {
      let values = this.tableKeys.map((key) => getRefPromise(this, key))
      return Promise.all(values)
    },
    /** 调用完edit()方法之后会自动调用此方法 */
    editAfter() {
      getAction('/online/api/listByUserIdCrmCustomer', {ownerUserId:this.userInfo().userLoginId}).then((res1) => {
        if (res1.success) {
          this.customerInfoList = res1.result;
        }
      })

      this.status5TimeVisible = false
      this.status6TimeVisible = false
      this.itemList = [
        {
          title: '仓储商机明细',
          key: 'item1',
          loading: false,
          dataSource: [],
          columns: [
            {
              title: '预计合同标的额(元)',
              key: 'estimatedSalesAmount',
              type: FormTypes.inputNumber,
              width: '200px',
              placeholder: '请输入${title}',
              defaultValue: '',
              validateRules: [
                { required: true, message: '请输入预计销售额!' },
                {
                  pattern: /(^[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/,
                  message: '请输入正确的金额!',
                },
              ],
            },
            {
              title: '仓库',
              key: 'inventoryId',
              type: FormTypes.select,
              width: '200px',
              placeholder: '请输入${title}',
              defaultValue: '',
              // dictCode: 'CrmWmsInventory,warehouseName,id',
              options: this.inventoryIdOptions,
              validateRules: [
                {
                  // 自定义函数校验 handler
                  handler(type, value, row, column, callback, target) {
                    if (value == '6666') {
                      row.waishow = true
                    } else {
                      row.waishow = false
                    }
                    callback(true) // true = 通过验证
                  },
                },
              ],
            },
            {
              title: '外仓名称',
              key: 'outerWarehouse',
              type: FormTypes.input,
              width: '200px',
              placeholder: '请输入${title}',
              defaultValue: '',
            },
            {
              title: '冷冻预估(托)',
              key: 'estimatedFreeze',
              type: FormTypes.inputNumber,
              width: '200px',
              placeholder: '请输入${title}',
              defaultValue: '',
              validateRules: [
                {
                  pattern: /(^[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/,
                  message: '请输入正确的数字!',
                },
              ],
            },
            {
              title: '冷藏预估(托)',
              key: 'estimatedRefrigerate',
              type: FormTypes.inputNumber,
              width: '200px',
              placeholder: '请输入${title}',
              defaultValue: '',
              validateRules: [
                {
                  pattern: /(^[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/,
                  message: '请输入正确的数字!',
                },
              ],
            },
            {
              title: '恒温预估(托)',
              key: 'estimatedConstant',
              type: FormTypes.inputNumber,
              width: '200px',
              placeholder: '请输入${title}',
              defaultValue: '',
              validateRules: [
                {
                  pattern: /(^[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/,
                  message: '请输入正确的数字!',
                },
              ],
            },
            {
              title: '常温预估(托)',
              key: 'estimatedNormal',
              type: FormTypes.inputNumber,
              width: '200px',
              placeholder: '请输入${title}',
              defaultValue: '',
              validateRules: [
                {
                  pattern: /(^[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/,
                  message: '请输入正确的数字!',
                },
              ],
            },
          ],
        },
        {
          title: '运输商机明细',
          key: 'item2',
          loading: false,
          dataSource: [],
          columns: [
            {
              title: '预计合同标的额(元)',
              key: 'estimatedSalesAmount',
              type: FormTypes.inputNumber,
              width: '200px',
              placeholder: '请输入${title}',
              defaultValue: '',
              validateRules: [
                { required: true, message: '请输入预计销售额!' },
                {
                  pattern: /(^[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/,
                  message: '请输入正确的金额!',
                },
              ],
            },
            {
              title: '运输类型',
              key: 'transType',
              type: FormTypes.select,
              width: '200px',
              placeholder: '请输入${title}',
              defaultValue: '',
              dictCode: 'DataDictionary,description,dictionaryCode,dictionaryTypeId=TRANS_TYPE',
              options: this.transTypeOptions,
            },
            {
              title: '业务执行仓',
              key: 'inventoryId',
              type: FormTypes.select,
              width: '200px',
              placeholder: '请输入${title}',
              defaultValue: '',
              // dictCode: 'CrmWmsInventory,warehouseName,id',
              options: this.inventoryIdOptions,
              validateRules: [
                { required: true, message: '请选择业务执行仓!' },
              ],
            },
            {
              title: '运输城市',
              key: 'transCity',
              type: FormTypes.input,
              width: '200px',
              placeholder: '请输入${title}',
              defaultValue: '',
            },
          ],
        },

        {
          title: '货代商机明细',
          key: 'item3',
          loading: false,
          dataSource: [],
          columns: [
            {
              title: '预计合同标的额(元)',
              key: 'estimatedSalesAmount',
              type: FormTypes.inputNumber,
              width: '200px',
              placeholder: '请输入${title}',
              defaultValue: '',
              validateRules: [
                { required: true, message: '请输入预计销售额!' },
                {
                  pattern: /(^[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/,
                  message: '请输入正确的金额!',
                },
              ],
            },
            {
              title: '是否贸易代理',
              key: 'tradeTypeId',
              type: FormTypes.select,
              width: '200px',
              placeholder: '请输入${title}',
              defaultValue: 'N',
              dictCode: 'DataDictionary,description,dictionaryCode,dictionaryTypeId=BOOL_DEFINE',
            },
            {
              title: '货代类型',
              key: 'forwardingType',
              type: FormTypes.select,
              width: '200px',
              placeholder: '请输入${title}',
              defaultValue: '',
              dictCode: 'DataDictionary,description,dictionaryCode,dictionaryTypeId=FWD_TYPE',
              options: this.forwardingTypeOptions,
            },
            {
              title: '口岸',
              key: 'portDesc',
              type: FormTypes.input,
              width: '200px',
              placeholder: '请输入${title}',
              defaultValue: '',
            },
            {
              title: '运输方式',
              key: 'shoppingType',
              type: FormTypes.select,
              width: '200px',
              placeholder: '请输入${title}',
              defaultValue: '',
              dictCode: 'DataDictionary,description,dictionaryCode,dictionaryTypeId=SHOP_TYPE',
              options: this.shoppingTypeOptions,
            },
            {
              title: '进出口',
              key: 'isImport',
              type: FormTypes.select,
              width: '200px',
              placeholder: '请输入${title}',
              defaultValue: '',
              dictCode: 'DataDictionary,description,dictionaryCode,dictionaryTypeId=IMPORT_TYPE',
              options: this.isImportOptions,
            },
          ],
        },
        {
          title: '库购商机明细',
          key: 'item4',
          loading: false,
          dataSource: [],
          columns: [
            {
              title: '预计合同标的额(元)',
              key: 'estimatedSalesAmount',
              type: FormTypes.inputNumber,
              width: '200px',
              placeholder: '请输入${title}',
              defaultValue: '',
              validateRules: [
                { required: true, message: '请输入预计销售额!' },
                {
                  pattern: /(^[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/,
                  message: '请输入正确的金额!',
                },
              ],
            },
            {
              title: '仓库',
              key: 'inventoryId',
              type: FormTypes.select,
              width: '200px',
              placeholder: '请输入${title}',
              defaultValue: '',
              // dictCode: 'CrmWmsInventory,warehouseName,id',
              options: this.inventoryIdOptions,
            },
          ],
        },
      ]
      if (this.model.followup == '100') {
        this.status5TimeVisible = true
        this.status6TimeVisible = true
      }
      if (this.model.followup == '90') {
        this.status5TimeVisible = true
      }
      if (this.customerId) {
        this.model.customerId = this.customerId
      }

      if(this.model.customerId){
        getAction('/online/api/listByUserIdCrmCustomer', {customerId:this.model.customerId}).then((res1) => {
          if (res1.success) {
            let list = res1.result;
            if(list.length>0){
              let map = list[0];
              if (!this.customerInfoList.includes(map)) {
                this.customerInfoList.push(map);
              }
            }
          }
        })
      }


      if (this.businessId) {
        this.model.businessId = this.businessId
      }
      let fieldval = pick(
        this.model,
        'typeId',
        'statusId',
        'nextTime',
        'customerId',
        'contactsId',
        'dealDate',
        'followup',
        'status5Time',
        'status6Time',
        'businessName',
        'money',
        'discountRate',
        'totalPrice',
        'remark',
        'createUserId',
        'ownerUserId',
        'createTime',
        'updateTime',
        'batchId',
        'roUserId',
        'rwUserId',
        'isEnd',
        'statusRemark',
        'lastTime',
        'inventoryId',
        'outerWarehouse'
      )
      this.$nextTick(() => {
        this.form.setFieldsValue(fieldval)
      })

      // 加载子表数据
      if (this.model.id) {
        let params1 = { id: this.model.id, typeId: '1' }
        this.requestSubTableData(this.url.list, params1, this.itemList[0])
        let params2 = { id: this.model.id, typeId: '2' }
        this.requestSubTableData(this.url.list, params2, this.itemList[1])
        let params3 = { id: this.model.id, typeId: '3' }
        this.requestSubTableData(this.url.list, params3, this.itemList[2])
        let params4 = { id: this.model.id, typeId: '4' }
        this.requestSubTableData(this.url.list, params4, this.itemList[3])
      }
    },
    /** 整理成formData */
    classifyIntoFormData(allValues) {
      let main = Object.assign(this.model, allValues.formValue)
      return {
        ...main, // 展开
        CrmBusinessItem: allValues.tablesValue[0].values,
        CrmBusinessItem1: allValues.tablesValue[1].values,
        CrmBusinessItem2: allValues.tablesValue[2].values,
        CrmBusinessItem3: allValues.tablesValue[3].values,
      }
    },
    chanageDealStatus(e) {
      console.log(e)
      if (e == 0) {
        this.form.setFieldsValue({ followup: 10 })
        this.status5TimeVisible = false
        this.status6TimeVisible = false
      }
      if (e == 1) {
        this.form.setFieldsValue({ followup: 20 })
        this.status5TimeVisible = false
        this.status6TimeVisible = false
      }
      if (e == 2) {
        this.form.setFieldsValue({ followup: 30 })
        this.status5TimeVisible = false
        this.status6TimeVisible = false
      }
      if (e == 3) {
        this.form.setFieldsValue({ followup: 40 })
        this.status5TimeVisible = false
        this.status6TimeVisible = false
      }
      if (e == 4) {
        this.form.setFieldsValue({ followup: 90 })
        this.status5TimeVisible = false
        this.status6TimeVisible = false
      }
      if (e == 5) {
        this.form.setFieldsValue({ followup: 90 })
        this.status5TimeVisible = true
        this.status6TimeVisible = false
      }
      if (e == 6) {
        this.form.setFieldsValue({ followup: 100 })
        this.status5TimeVisible = true
        this.status6TimeVisible = true
      }
      if (e == 7) {
        this.form.setFieldsValue({ followup: 0 })
        this.status5TimeVisible = false
        this.status6TimeVisible = false
      }

      if (this.form.getFieldsValue().followup == undefined) {
        this.form.setFieldsValue({ followup: 50 })
        this.status5TimeVisible = false
        this.status6TimeVisible = false
      }
    },
    validateError(msg) {
      if (msg) {
        this.isHandleOk = false
      }
      this.$message.error(msg)
    },
    popupCallback(row) {
      this.form.setFieldsValue(
        pick(
          row,
          'typeId',
          'statusId',
          'nextTime',
          'customerId',
          'contactsId',
          'dealDate',
          'followup',
          'status5Time',
          'status6Time',
          'businessName',
          'money',
          'discountRate',
          'totalPrice',
          'remark',
          'createUserId',
          'ownerUserId',
          'createTime',
          'updateTime',
          'batchId',
          'roUserId',
          'rwUserId',
          'isEnd',
          'statusRemark',
          'lastTime',
          'inventoryId',
          'outerWarehouse'
        )
      )
    },
    /** 发起请求，自动判断是执行新增还是修改操作 */
    request(formData) {
      let url = this.url.add,
        method = 'post'
      if (this.model.id) {
        url = this.url.edit
        method = 'put'
      }
      this.confirmLoading = true
      httpAction(url, formData, method)
        .then((res) => {
          if (res.success) {
            this.$message.success('成功')
            this.$emit('ok')
            if (this.model.id) {
              this.$emit('reload', { id: this.model.id })
            }
            this.close()
          } else {
            this.$message.warning(res.message)
          }
        })
        .finally(() => {
          this.confirmLoading = false
        })
    },

    // getFitstContract
    // getFitstContract(e) {
    //   getAction('/online/api/getCrmCustomer', { id: e }).then((res) => {
    //     if (res.success) {
    //       this.$nextTick(() => {
    //         this.form.setFieldsValue({ contactsId: res.result.contactsId })
    //       })
    //     }
    //   })
    // },
  },
}
</script>

<style lang="less" scoped>
/deep/ .ant-modal-mask {
  z-index: 98;
  background-color: rgb(245, 246, 249);
}

/deep/ .ant-modal-wrap {
  z-index: 99;
}

/deep/ .ant-modal-title {
  color: #333;
  font-weight: 700;
  font-size: 17px;
}
</style>